<template>
    <div class="content-wrap">
        <div class="content-top-box">
            <!-- 搜索区域 -->
            <ul class="search-container">
                <li>
                    <span class="search-item-name">标题：</span>
                    <el-input
                        class="search-item-content search-item-text"
                        placeholder="请输入标题"
                        v-model="title"
                        clearable
                        maxlength="11"
                        @clear="clearTitleFn"
                    >
                    </el-input>
                </li>
                <li>
                    <span class="search-item-name">发布时间：</span>
                    <el-date-picker
                        v-model="date"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        @change="changeDate">
                    </el-date-picker>
                </li>
                <li>
                    <span class="search-item-name">文章类型：</span>
                    <el-select
                        class="search-item-content"
                        v-model="articleType" 
                        placeholder="请选择"
                        clearable
                        @change="changeArticleType"
                    >
                        <el-option
                            v-for="item in articleTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </li>
                <li>
                    <el-button class="search-btn" type="primary" icon="el-icon-search" @click="searchFn" v-if="searchBtn">查询</el-button>
                    <el-button class="search-btn" type="primary" icon="el-icon-plus" @click="addFn" v-if="addBtn">新增</el-button>
                </li>
            </ul>
        </div>

        <div class="content-bottom-box">
            <!-- 表格 -->
            <div class="content-form-box">
                <el-table
                    v-loading="loadingFlag"
                    :data="tableData"
                    :height="tableHeight"
                    ref="table"
                    border
                    stripe
                    style="width: 100%"
                >
                    <el-table-column
                        prop="serialNumber"
                        label="序号"
                        width="60"
                        :show-overflow-tooltip="true"
                        fixed
                        >
                    </el-table-column>
                    <el-table-column
                        label="文章类型"
                        width="100"
                        :show-overflow-tooltip="true"
                        fixed
                        >
                        <template slot-scope="scope">
                            <span>{{scope.row.type == 1 ? '平台资讯' : '最新动态'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="title"
                        label="文章标题"
                        width="360"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        label="图片预览"
                        width="120"
                        >
                        <template slot-scope="scope">
                            <el-button @click="checkImgFn(scope.row.picUrl)" type="text" size="small">【查看】</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="url"
                        label="链接"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="发布时间"
                        width="180"
                        :show-overflow-tooltip="true"
                        >
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed="right"
                        width="180">
                        <template slot-scope="scope">
                            <el-button @click="editInfoFn(scope.row.id)" type="text" size="small" v-if="editBtn">编辑</el-button>
                            <el-button @click="upAndDownInfoFn(scope.row.id, scope.row.status)" type="text" size="small" v-if="scope.row.status == 99 && onBtn">重新上架</el-button>
                            <el-button @click="upAndDownInfoFn(scope.row.id, scope.row.status)" type="text" size="small" v-if="scope.row.status == 1 && offBtn">下架</el-button>
                            <el-button @click="deleteInfoFn(scope.row.id)" type="text" size="small" v-if="deleteBtn">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 页码 -->
            <div class="content-Page-container">
                <BaseFormPage 
                    :pagination="pagination"
                    @cFirstPageFn="cFirstPageFn"
                    @cLastPageFn="cLastPageFn"
                    @cJumpPageFn="cJumpPageFn"
                    @cPreFn="cPreFn"
                    @cNextFn="cNextFn"
                    @cRefreshFn="cRefreshFn"
                    >
                </BaseFormPage>
            </div>
        </div>

        <!-- 新增/编辑 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFlag"
            width="714px"
            :show-close="false"
            center
            class="news-dialog-content">
            <div class="dialog-wrap">
                <div class="dialog-wrap-left">
                    <el-form 
                        :model="ruleForm" 
                        :rules="rules" 
                        ref="ruleForm" 
                        :hide-required-asterisk="true"
                        label-width="100px" 
                        class="form-box"
                    >
                        <el-form-item label="文章类型：" prop="articleType">
                            <el-select v-model="ruleForm.articleType" placeholder="请选择">
                                <el-option label="平台资讯" value="1"></el-option>
                                <!-- <el-option label="最新动态" value="2"></el-option> -->
                            </el-select>
                        </el-form-item>
                        <el-form-item label="文章标题：" prop="articleTitle">
                            <el-input 
                                v-model="ruleForm.articleTitle" 
                                placeholder="请输入文章标题，长度2~20字" 
                                maxlength="20"
                                show-word-limit>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="发布形式：">
                            <el-radio-group v-model="ruleForm.publishType" @change="changePublishTypeFn">
                                <!-- <el-radio label="链接URL"></el-radio> -->
                                <el-radio label="自定义发布"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="链接URL：" prop="linkUrl" v-if="publishType == 1">
                            <el-input v-model="ruleForm.linkUrl" placeholder="请输入链接URL" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="文章来源：" prop="articleSource">
                            <el-input 
                                v-model="ruleForm.articleSource" 
                                placeholder="请输入文章来源" 
                                maxlength="20">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="发布状态：">
                            <el-radio-group v-model="ruleForm.publishState">
                                <el-radio label="上架"></el-radio>
                                <el-radio label="下架"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="dialog-wrap-right">
                    <div class="img-box">
                        <i class="el-icon-picture-outline" v-if="!articleImg"></i>
                        <img :src="articleImg" alt="" @click="checkImgFn(articleImg)">
                    </div>
                    <el-upload
                        class="upload-demo"
                        ref="uploadImg"
                        action="http://cs.umubao.com/ymfarm-1.0-SNAPSHOT/api/common/uploadFile"
                        :on-success="uploadSuccess"
                        :before-upload="beforeUpload"
                        :before-remove="beforeRemove"
                        multiple
                        name="multipartFile"
                        :limit="1"
                        :on-exceed="limitExceed"
                        :on-remove="onRemove">
                        <el-button size="small" type="success">资讯封面图片{{isEditFlag ? '编辑' : '上传'}}</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件，且不超过2M</div>
                    </el-upload>
                </div>
            </div>
            <div class="news-box" v-if="publishType == 2">
                <span class="news-text">资讯内容：</span>
                <div class="news-content">
                    <quill-editor 
                        ref="text" 
                        v-model="content" 
                        class="myQuillEditor" 
                        :options="editorOption" 
                        @change="editorChange($event)"
                    />
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="resetForm('ruleForm')">取 消</el-button>
                <el-button size="small" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 查看图片 -->
        <el-dialog
            title="查看图片"
            :visible.sync="imgDialogFlag"
            width="400px"
            center
            class="article-check-wrap">
            <div class="demo-image__error">
                <div class="block">
                    <el-image :src="imgSrc"></el-image>
                </div>
            </div>
        </el-dialog>

        <!-- 上下架提示 -->
        <el-dialog
            :title="upAndDownDialogTitle"
            :visible.sync="upAndDownDialogFlag"
            width="340px"
            :show-close="false"
            top="30vh"
            center
            class="news-delete-wrap">
            <span>请确认是否{{upAndDownDialogTitle}}此资讯？</span>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="upAndDownDialogFlag = false">取 消</el-button>
                <el-button size="small" type="primary" @click="upOrDownFn">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示 -->
        <el-dialog
            title="删除"
            :visible.sync="delDialogFlag"
            width="340px"
            :show-close="false"
            top="30vh"
            center
            class="news-delete-wrap">
            <span>请确认是否删除此资讯？</span>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="delDialogFlag = false">取 消</el-button>
                <el-button size="small" type="primary" @click="deleteFn">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Storage from "@/utils/storage";
import BaseFormPage from '@/components/BaseFormPage'
export default {
    components: {
        quillEditor,
        BaseFormPage
    },
    data() {
        return {
            loadingFlag: false,         //表格数据加载状态
            dialogFlag: false,          //弹窗显示状态
            imgDialogFlag: false,       //查看图片
            delDialogFlag: false,       //删除弹窗显示状态
            upAndDownDialogFlag: false, //上下架显示状态
            title: '',
            date: '',
            startTime: '',
            endTime: '',
            articleType: '',
            articleTypeOptions: [
                {
                    value: '1',
                    label: '平台资讯'
                },
                {
                    value: '2',
                    label: '最新动态'
                },
            ],

            pageIndex: 1,
            pageSize: 20,
            tableHeight: 200,           //表格初始高度
            tableData: [],              //表格数据
            pagination: {               //分页数据
                loadingFlag: false,     //数据加载状态
                currentPage: 1,         //当前页
                totalPage: 1,           //总页数
                totalNum: 0,            //总条数
                firstNum: 0,            //分页显示起始值
                endNum: 0               //分页显示结束值
            },

            imgSrc: '',

            bannerType: '',
            bannerTypeOptions: [
                {
                    value: '1',
                    label: '首页banner'
                },
            ],
            dialogTitle: '',
            upAndDownDialogTitle: '',
            bannerTitle: '',
            bannerUrl: '',
            date: '',
            radio: '1',
            checked: false,
            sortNum: '',

            content: '',
            editorOption: {
                modules:{
                    toolbar:[
                        [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //标题
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }], //列表
                        [{ 'align': [] }], //文本对齐方式
                        [{ 'color': [] }, { 'background': [] }], //字体/背景色
                        ['bold', 'italic', 'underline', 'strike'], //字体处理
                        ['blockquote', 'code-block'], //引用/代码
                    ]
                }
            },

            upOrDownId: '',
            upOrDownStatus: '',
            currentDelId: '',

            articleImg: '',
            isEditFlag: false,
            publishType: '',
            currentEditId: '',

            ruleForm: {
                articleType: '',
                articleTitle: '',
                publishType: '',
                linkUrl: '',
                articleSource: '',
                publishState: '上架'
            },
            rules: {
                articleType: [
                    { required: true, message: '请选择文章类型', trigger: 'change' }
                ],
                articleTitle: [
                    { required: true, message: '请输入文章标题', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                articleSource: [
                    { required: true, message: '请输入文章来源', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                // linkUrl: [
                //     { required: true, message: '请输入链接URL', trigger: 'blur' },
                // ],
            },

            searchBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(271) == -1 ? false : true,
            addBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(272) == -1 ? false : true,
            editBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(273) == -1 ? false : true,
            onBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(274) == -1 ? false : true,
            offBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(275) == -1 ? false : true,
            deleteBtn: (JSON.parse(Storage.get('roleAuthIdArr'))).indexOf(276) == -1 ? false : true,
        }
    },
    created() {
        this.getListData()
    },
    methods: {
        getListData() {
            this.loadingFlag = true;
            this.pagination.loadingFlag = true;
            let params = {
                title: this.title,
                startTime: this.startTime,
                endTime: this.endTime,
                type: this.articleType,
                pgCt: this.pageIndex,
                pgSz: this.pageSize
            }
            if(!this.title) {
                delete params.title
            }
            if(!this.date) {
                delete params.startTime
                delete params.endTime
            }
            if(!this.articleType) {
                delete params.type
            }
            this.$http.get('/bulletin/list', params)
                .then((res) => {
                    if(res.data.records.length > 0) {
                        this.pagination.totalPage = res.data.pages
                        this.pagination.totalNum = res.data.total
                        
                        res.data.records.forEach((item, index) => {
                            //列表下标
                            item.index = index
                            //列表序号
                            item.serialNumber = ((this.pageIndex - 1) * this.pageSize) + (index + 1)
                            item.startTime   = item.startTime || '--'
                            item.endTime     = item.endTime || '--'
                        })
                        this.pagination.firstNum = res.data.records[0].serialNumber
                        this.pagination.endNum = res.data.records[res.data.records.length-1].serialNumber
                    }else{
                        this.pagination.currentPage = 1
                        this.pagination.totalPage = 1
                        this.pagination.totalNum = 0
                        this.pagination.firstNum = 0
                        this.pagination.endNum = 0
                    }
                    this.tableData  = res.data.records;
                })
                .then(() => {
                    this.tableHeightFn();
                    this.loadingFlag = false;
                    this.pagination.loadingFlag = false;
                })
        },
        tableHeightFn() { //表格高度
            let tableDataLength = this.tableData.length;
            let minHeight = tableDataLength == 0 ? 0 : 80;
            this.$nextTick(function () {
                this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - minHeight;
                if(this.tableData.length <= 0) {
                    this.tableHeight = '60vh'
                }
                
                let self = this;
                window.onresize = function() {
                    self.tableHeight = window.innerHeight - self.$refs.table.$el.offsetTop - minHeight;
                    self.tableHeight = self.tableHeight < 200 ? 200 : self.tableHeight;
                }
            })
        },
        resetPageIndex() { //重置页码
            this.pagination.currentPage = 1;
            this.pageIndex = 1;
        },
        clearTitleFn() { //清空标题
            this.resetPageIndex()
            this.getListData()
        },
        searchFn() { //搜索
            this.resetPageIndex()
            this.getListData()
        },
        addFn() { //新增
            this.dialogFlag = true;
            this.dialogTitle = '新增';
            this.isEditFlag = false;
        },
        changeDate() { //选择时间
            if(this.date) {
                this.startTime = this.date[0]
                this.endTime = this.date[1].replace('00:00:00', '23:59:59')
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.resetPageIndex()
            this.getListData()
        },
        changeArticleType() { //选择状态
            this.resetPageIndex()
            this.getListData()
        },
        checkImgFn(src) { //查看图片
            this.imgSrc = src
            this.imgDialogFlag = true
        },
        editInfoFn(id) { //编辑
            this.dialogFlag = true;
            this.dialogTitle = '编辑';
            this.isEditFlag = true;
            this.currentEditId = id;
            this.getDetailFn(id);
        },
        getDetailFn(id) {
            this.$http.get('/bulletin/getById/' + id)
                .then((res) => {
                    this.ruleForm.articleType = res.data.type + ''
                    this.ruleForm.articleTitle = res.data.title
                    this.ruleForm.publishType = res.data.content ? '自定义发布' : '链接URL'
                    this.publishType = res.data.content ? 2 : 1
                    this.content = res.data.content
                    this.articleImg = res.data.picUrl
                    this.ruleForm.articleSource = res.data.source
                    this.ruleForm.linkUrl = res.data.url
                    this.ruleForm.publishState = res.data.status == 1 ? '上架' : '下架'
                })
        },
        upAndDownInfoFn(id, status) { //上下架
            this.upOrDownId = id;
            this.upOrDownStatus = status == 1 ? 99 : 1;
            this.upAndDownDialogFlag = true;
            this.upAndDownDialogTitle = status == 1 ? '下架' : '重新上架'
        },
        upOrDownFn() {
            let params = {
                id: this.upOrDownId,
                status: this.upOrDownStatus
            }

            this.$http.post('/bulletin/addOrUpdate', params)
                .then((res) => {
                    this.upAndDownDialogFlag = false;
                    this.$message({
                        message: this.upAndDownDialogTitle == '下架' ? '操作成功，已下架' : '操作成功，已重新上架',
                        type: 'success'
                    });
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },
        deleteInfoFn(id) { //删除
            this.delDialogFlag = true;
            this.currentDelId = id;
        },
        deleteFn() {
            this.$http.get('/bulletin/delete/' + this.currentDelId)
                .then((res) => {
                    this.delDialogFlag = false;
                    this.$message({
                        message: '已删除',
                        type: 'success'
                    });
                    setTimeout(() => {
                        this.searchFn()
                    }, 1000)
                })
        },
        cFirstPageFn(pageNum) { //首页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cLastPageFn(pageNum) { //尾页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cJumpPageFn(pageNum) { //页码跳转
            this.pageIndex = pageNum;
            this.getListData()
        },
        cPreFn(pageNum) { //上一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        cNextFn(pageNum) { //下一页
            this.pageIndex = pageNum;
            this.getListData()
        },
        resetParams() { //重置参数
            this.phone = ''
            this.userName = ''
            this.date = ''
            this.startPurchaseTime = ''
            this.endPurchaseTime = ''
            this.purchaseType = ''
            this.detailData = {}
            this.tableData = []
            this.pageIndex = 1
            this.pageSize = 20
            this.pagination = {
                loadingFlag: false,
                currentPage: 1,
                totalPage: 1,
                totalNum: 0,
                firstNum: 0,
                endNum: 0
            }
        },
        cRefreshFn() { //刷新
            this.resetParams()
            this.getListData()
        },

        changeBannerType() {
            
        },

        submit() {
            
        },

        editorChange(e) {
            
        },


        submitForm(formName) { //确认提交
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.articleImg) {
                        this.addOrEditArticleFn()
                    }else{
                        this.$message.error('请上传资讯图片');
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addOrEditArticleFn() { //提交请求
            let params = {
                'id': this.currentEditId,
                'type': this.ruleForm.articleType,
                'title': this.ruleForm.articleTitle,
                'publishType': this.ruleForm.publishType == '链接URL' ? 1 : 2,
                'picUrl': this.articleImg,
                'url': this.ruleForm.linkUrl,
                'content': this.content,
                'source': this.ruleForm.articleSource,
                'status': this.ruleForm.publishState == '上架' ? 1 : 99,
            }
            if(!this.isEditFlag) { //新增
                delete params.id
            }

            if(this.ruleForm.publishType == '链接URL') {
                delete params.content
            }else{
                delete params.url
            }

            // console.log('params:', JSON.stringify(params))

            this.$http.post('/bulletin/addOrUpdate', params)
                .then((res) => {
                    this.dialogFlag = false;
                    this.$message({
                        message: this.isEditFlag ? '编辑成功' : '新增成功',
                        type: 'success'
                    });
                    setTimeout(() => {
                        this.searchFn()
                        this.resetForm('ruleForm')
                    }, 1000)
                })
        },
        resetForm(formName) { //重置表单内容
            this.$refs[formName].resetFields();
            this.dialogFlag = false;
            this.articleImg = '';
            this.publishType = '';
            this.ruleForm.publishType = '';
            this.content = '';
            this.$refs.uploadImg.clearFiles();
        },

        changePublishTypeFn() { //选择发布形式
            if(this.ruleForm.publishType == '链接URL') {
                this.publishType = 1;
            }else{
                this.publishType = 2;
            }
        },

        limitExceed(files, fileList) { //图片个数限制
            this.$message.warning(`当前限制上传 1 个文件，本次选择了 ${files.length} 个文件，若需要更改图片，请删除已上传文件`);
        },
        uploadSuccess(res, file) { //图片上传成功
            this.articleImg = res.data.url;
        },
        beforeUpload(file) { //图片格式大小限制
            const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 jpg/png 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        beforeRemove(file, fileList) { //移除已上传图片
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        onRemove() { //移除图片成功
            this.articleImg = "";
        }
    }
}
</script>

<style lang="scss">
    .news-dialog-content {
        .dialog-wrap {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .dialog-wrap-left {
                width: 390px;
                .form-box {
                    .el-select .el-input.el-input--suffix {
                        width: 290px;
                    }
                    .el-date-editor--daterange.el-input__inner {
                        width: 290px;
                    }
                    .el-date-editor .el-range-input {
                        width: 33%;
                    }
                    .el-date-editor .el-range-separator {
                        width: 16%;
                    }
                }
                
            }
            .dialog-wrap-right {
                width: 224px;
                text-align: center;
                .img-box {
                    width: 224px;
                    height: 138px;
                    border: 1px solid #D0CFCF;
                    img {
                        width: 100%;
                        height: 100%;
                    }
                    i {
                        font-size: 44px;
                        color: #D0CFCF;
                        line-height: 130px;
                    }
                }
                button {
                    margin-top: 24px;
                }
            }
        }
        .news-box {
            display: flex;
            margin-top: 14px;
            .news-text {
                padding-left: 18px;
                width: 102px;
            }
            .news-content {
                width: 570px;
                .ql-container {
                    height: 200px;
                }
            }
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }

    .article-check-wrap {
        .el-dialog__body {
            text-align: center;
        }
    }
    
    .news-delete-wrap {
        .el-dialog__header {
            padding: 18px 20px;
        }
        .el-dialog__body {
            padding-bottom: 24px;
            text-align: center;
        }
        .el-dialog__footer {
            .el-button+.el-button {
                margin-left: 50px;
            }
        }
    }
</style>